import SparkMD5 from 'spark-md5'

let running = false // running用于判断是否正在计算md5

// 计算blob的md5码
export const doNormalTest = (file: Blob) => {
  return new Promise<string>((resolve, reject) => {
    if (running) {
      reject(Error('In the calculation, please wait a second.'))
      return
    }
    const fileReader = new FileReader()
    fileReader.onload = function (e: any) {
      running = false
      if (file.size !== e.target.result.length) {
        // 如果两者不一致说明读取出错
        reject(Error('read error'))
      } else {
        const md5 = SparkMD5.hashBinary(e.target.result)
        resolve(md5)
      }
    }
    fileReader.onerror = function () {
      running = false
      reject(Error('fileReader.onerror'))
    }
    running = true
    fileReader.readAsBinaryString(file)
  })
}

/* 根据md5，同文件生成不变的码，伪唯一，以便重复上传相同文件时可覆盖原文件 */
export const md5ID = async (file: File, key: number | string = '') => {
  // key一般为当前用户的userId
  const md5 = await doNormalTest(file)
  const size = file.size.toString(36) // 压缩为36进制
  return `${key}${md5}${size}`
}

export default {
  doNormalTest,
  md5ID
}
